<?php
 namespace Admin\Model;
/**
 * 订单服务类
 */
class OrdersModel extends BaseModel {
	/**
	 * 获取订单详细信息
	 */
	 public function getDetail(){
	 	$m = M('orders');
	 	$id = (int)I('id',0);
		$sql = "select o.*,s.shopName from __PREFIX__orders o
	 	         left join __PREFIX__shops s on o.shopId=s.shopId 
	 	         where o.orderFlag=1 and o.orderId=".$id;
		$rs = $this->queryRow($sql);
		//获取用户详细地址
		$sql = 'select communityName,a1.areaName areaName1,a2.areaName areaName2,a3.areaName areaName3 from __PREFIX__communitys c 
		        left join __PREFIX__areas a1 on a1.areaId=c.areaId1 
		        left join __PREFIX__areas a2 on a2.areaId=c.areaId2
		        left join __PREFIX__areas a3 on a3.areaId=c.areaId3
		        where c.communityId='.$rs['communityId'];
		//$cRs = $this->queryRow($sql);
		$rs['userAddress'] = $cRs['areaName1'].$cRs['areaName2'].$cRs['areaName3'].$cRs['communityName'].$rs['userAddress'];
		//获取日志信息
		$m = M('log_orders');
		$sql = "select lo.*,u.loginName,u.userType,s.shopName from __PREFIX__log_orders lo
		         left join __PREFIX__users u on lo.logUserId = u.userId
		         left join __PREFIX__shops s on u.userType!=0 and s.userId=u.userId
		         where lo.logType=0 and orderId=".$id;
		$rs['log'] = $this->query($sql);
		//获取相关商品
		$sql = "select og.*,g.goodsThums,g.goodsName,g.goodsId from __PREFIX__order_goods og
			        left join __PREFIX__goods g on og.goodsId=g.goodsId
			        where og.orderId = ".$id;
		$rs['goodslist'] = $this->query($sql);
		//获取物流信息
		$sql = "select oe.*,e.* from __PREFIX__order_express oe left join __PREFIX__express e on oe.expressId = e.id where orderId = ".$id;
		$rs['express'] = $this->query($sql);
		return $rs;
	 }
	 /**
	  * 获取订单信息
	  */
	 public function get(){
	 	$m = M('orders');
	 	return $m->where('isRefund=1 and payType in(1,2,3) and isPay=1 and orderFlag=1 and orderStatus in (-1,-4,-6,-7) and orderId='.(int)I('id'))->find();
	 }
	 /**
	  * 订单分页列表
	  */
     public function queryByPage($deliverType){
        $m = M('goods');
        $shopName = I('shopName');
     	$orderNo = I('orderNo');
     	$areaId1 = (int)I('areaId1',0);
     	$areaId2 = (int)I('areaId2',0);
     	$areaId3 = (int)I('areaId3',0);
     	$isGroup = (int)I('isGroup',0);
		$isSeckill = (int)I('isSeckill',0);
     	$orderStatus = (int)I('orderStatus',-9999);
         $orderType=1;
         if($isGroup)$orderType=3;
         if($isSeckill)$orderType=2;
	 	$sql = "select o.orderId,o.orderNo,o.needPay,o.totalMoney,o.orderStatus,o.deliverMoney,o.payType,o.createTime,s.shopName,o.userName from __PREFIX__orders o
	 	         left join __PREFIX__shops s on o.shopId=s.shopId  where o.orderFlag=1 and o.deliverType = {$deliverType} and o.orderType=$orderType ";
	 	if($areaId1>0)$sql.=" and s.areaId1=".$areaId1;
	 	if($areaId2>0)$sql.=" and s.areaId2=".$areaId2;
	 	if($areaId3>0)$sql.=" and s.areaId3=".$areaId3;
	 	if($shopName!='')$sql.=" and (s.shopName like '%".$shopName."%' or s.shopSn like '%".$shopName."%')";
	 	if($orderNo!='')$sql.=" and o.orderNo like '%".$orderNo."%' ";
	 	if($orderStatus!=-9999 && $orderStatus!=-100)$sql.=" and o.orderStatus=".$orderStatus;
	 	if($orderStatus==-100)$sql.=" and o.orderStatus in(-6,-7)";
	 	$sql.=" order by orderId desc";
		$page = $m->pageQuery($sql);
		//获取涉及的订单及商品
		if(count($page['root'])>0){
			$orderIds = array();
			foreach ($page['root'] as $key => $v){
				$orderIds[] = $v['orderId'];
			}
			$sql = "select og.orderId,og.goodsThums,og.goodsName,og.goodsId from __PREFIX__order_goods og
			        where og.orderId in(".implode(',',$orderIds).")";
		    $rs = $this->query($sql);
		    $goodslist = array();
		    foreach ($rs as $key => $v){
		    	$goodslist[$v['orderId']][] = $v;
		    }
		    foreach ($page['root'] as $key => $v){
		    	$page['root'][$key]['goodslist'] = $goodslist[$v['orderId']];
		    }
		}
		return $page;
	 }
	 /**
	  * 获取退款列表
	  */
     public function queryRefundByPage(){
        $m = M('goods');
        $shopName = I('shopName');
     	$orderNo = I('orderNo');
     	$isRefund = (int)I('isRefund',-1);
     	$areaId1 = (int)I('areaId1',0);
     	$areaId2 = (int)I('areaId2',0);
     	$areaId3 = (int)I('areaId3',0);
	 	$sql = "select o.orderId,o.orderNo,o.totalMoney,o.orderStatus,o.isRefund,o.deliverMoney,o.payType,o.createTime,s.shopName,o.userName from __PREFIX__orders o
	 	         left join __PREFIX__shops s on o.shopId=s.shopId  where o.orderFlag=1 and o.orderStatus in (-1,-4) and payType in(1,2,3) and isPay=1 ";
	 	if($areaId1>0)$sql.=" and s.areaId1=".$areaId1;
	 	if($areaId2>0)$sql.=" and s.areaId2=".$areaId2;
	 	if($areaId3>0)$sql.=" and s.areaId3=".$areaId3;
	 	if($isRefund>-1)$sql.=" and o.isRefund=".$isRefund;
	 	if($shopName!='')$sql.=" and (s.shopName like '%".$shopName."%' or s.shopSn like '%".$shopName."%')";
	 	if($orderNo!='')$sql.=" and o.orderNo like '%".$orderNo."%' ";
	 	$sql.=" order by orderId desc";  
		$page = $m->pageQuery($sql);
		//获取涉及的订单及商品
		if(count($page['root'])>0){
			$orderIds = array();
			foreach ($page['root'] as $key => $v){
				$orderIds[] = $v['orderId'];
			}
			$sql = "select og.orderId,og.goodsThums,og.goodsName,og.goodsId from __PREFIX__order_goods og
			        where og.orderId in(".implode(',',$orderIds).")";
		    $rs = $this->query($sql);
		    $goodslist = array();
		    foreach ($rs as $key => $v){
		    	$goodslist[$v['orderId']][] = $v;
		    }
		    foreach ($page['root'] as $key => $v){
		    	$page['root'][$key]['goodslist'] = $goodslist[$v['orderId']];
		    }
		}
		return $page;
	 }
	 /**
	  * 退款
	  */
	 public function refund(){
	 	$rd = array('status'=>-1);
	 	$m = M('orders');
	 	$rs = $m->where('isRefund=1 and orderFlag=1 and orderStatus in (-1,-4,-6,-7) and payType in(1,2,3) and isPay=1 and orderId='.I('id'))->find();
	 	if($rs['orderId']!=''){
	 		$data = array();
	 		$data['isRefund'] = 2;
	 		$data['refundRemark'] = I('content');
	 	    $rss = $m->where("orderId=".(int)I('id',0))->save($data);
	 	    //修改退款表
	 	    $data = array();
	 	    $data['pf_status'] = 1;//平台退款状态
	 	    $data['actual_money'] = $rs['needPay'];//实际退款金额
	 	    $data['pf_time'] = time();//平台处理时间
	 	    $data['way'] = I('way');//退款方式
	 	    $m = M('Refund');
	 	    $m->where('orderid ='.I('id'))->save($data);
	 	    //增加退款消费记录
			$moneyRModel = D('Money_record');
			$mr = array();
			$mr['type'] = 2;
			$mr['money'] = $data['actual_money'];
			$mr['time'] = time();
			$mr['ip'] = $_SERVER['REMOTE_ADDR'];
			$mr['orderNo'] = $rs['orderNo'];
			$mr['IncDec'] = 1;
			$mr['userid'] = $rs['userId'];
            if(I('content')==''){
                $mr['remark'] = '订单退款';
            }else{
                $mr['remark'] = I('content');

            }

			$mr['payWay'] = I('way');
	 	    //退款到余额
	 	    $m = M('Users');
	 	    $userMoney = $m->where('userId ='.$rs['userId'])->getField('userMoney');
	 	    if(I('way')=='0'){
	 	    	$lastMoney = $userMoney + $data['actual_money'];
	 	    	$m->where('userId ='.$rs['userId'])->setField('userMoney',$lastMoney);		
				$mr['balance'] = $lastMoney;
	 	    }else{
				$mr['balance'] = $userMoney;
	 	    }
			$moneyRModel->add($mr);
			if(false !== $rs){
				$rd['status']= 1;
			}else{
				$rd['status']= -2;
			}
	 	}
	 	return $rd;
	 }

	/**
	  * 获取退款中订单的数量
	  */
	 public function queryIsRefundNum(){
	 	$rd = array('status'=>-1);
	 	$m = M('Orders');
	 	$sql="select count(*) counts from __PREFIX__orders o left join __PREFIX__shops s on o.shopId=s.shopId  where o.orderFlag=1 and o.orderStatus in (-1,-4) and payType in(1,2,3) and isPay=1 and isRefund = 1";
	 	$rs = $this->query($sql);
	 	$rd['num'] = $rs[0]['counts'];
	 	return $rd;
	 }
	 
	 
	 
	 
	 
	 
	 
	 
	 /**
	  * 获取会员排行数据（这里默认是以订单数量排的）
	  * @param string $page
	  * @param string $pageSize
	  * @param $map
	  * @return mixed
	  */
	 public function getOrderCountDesc($page='',$pageSize='',$map)
	 {
	 	$offset = ($page-1) * $pageSize;
	 	$m = M('Orders');
	 	return $m->join('LEFT JOIN oto_users ON oto_orders.userId = oto_users.userId')
	 	->where($map)
	 	->field('oto_users.userName,count(oto_orders.userId) as orderCount,sum(totalMoney) as money,oto_orders.userId')
	 	->group('oto_orders.userId')
	 	->order('count(oto_orders.userId) desc,sum(totalMoney) desc')
	 	->limit($offset,$pageSize)
	 	->select();
	 }
	 
	 /**
	  * 获取会员排行符合条件的条数，用于分页
	  * @return int
	  */
	 public function getOrderCount($map)
	 {
	 	$m = M('Orders');
	 	$sql = "select count(*) from oto_orders WHERE ".$map." GROUP BY userId";
	 	$count =  count($this->query($sql));
	 	return $count;
	 }
	 
	 /**
	  * 获取会员排行导出数据
	  * @param $startDate
	  * @param $endDate
	  * @return mixed
	  */
	 public function derivedOrder($startDate,$endDate){
	 	$m = M('Orders');
	 	$where = "orderStatus = 4 ";
	 	if($startDate != ""){
	 		$where.="AND oto_orders.createTime >= '$startDate'";
	 	}
	 	if($endDate != ""){
	 		$where.="AND oto_orders.createTime < '$endDate'";
	 	}
	 	return $m->join('LEFT JOIN oto_users ON oto_orders.userId = oto_users.userId')
	 	->where($where)
	 	->field('oto_users.userName,count(oto_orders.userId) as orderCount,sum(totalMoney) as money,oto_orders.userId')
	 	->group('oto_orders.userId')
	 	->order('count(oto_orders.userId) desc,sum(totalMoney) desc')
	 	->select();
	 }
	 
	 
	 
	 
	 
	 /**
	  * 获取销售排行数据
	  * @param string $page
	  * @param string $pageSize
	  * @param $map
	  * @return mixed
	  */
	 public function goodsOrder($page='',$pageSize='',$map){
	 	$m = M('Orders');
	 	$offset = ($page-1) * $pageSize;
	 	return $m->join('LEFT JOIN oto_order_goods ON oto_orders.orderId = oto_order_goods.orderId')
	 	->where($map)
	 	->field('goodsName,goodsId,count(goodsNums) as goodsCount,sum(goodsPrice) as sum,avg(goodsPrice) as avg')
	 	->group('goodsName')
	 	->limit($offset,$pageSize)
	 	->order('count(goodsId) desc,sum(goodsPrice) desc')
	 	->select();
	 }
	 
	 /**
	  * 获取销售排行总数用于分页
	  * @return int
	  */
	 public function goodsOrderCount($map){
	 	$m = M('Orders');
	 	$sql = 'select * from oto_orders LEFT JOIN oto_order_goods ON oto_orders.orderId = oto_order_goods.orderId WHERE '.$map." GROUP BY oto_order_goods.goodsName";
	 	$count = $m->query($sql);
	 	return count($count);
	 }
	 
	 /**
	  * 导出销售排行数据
	  * @param $startDate
	  * @param $endDate
	  * @return mixed
	  */
	 public function derivedGoods($startDate,$endDate){
	 	$m = M('Orders');
	 	$where = "orderStatus = 4 ";
	 	if($startDate != ""){
	 		$where.="AND createTime >= '$startDate'";
	 	}
	 	if($endDate != ""){
	 		$where.="AND createTime < '$endDate'";
	 	}
	 	return $m->join('LEFT JOIN oto_order_goods ON oto_orders.orderId = oto_order_goods.orderId')
	 	->where($where)
	 	->field('goodsName,goodsId,count(goodsNums) as goodsCount,sum(goodsPrice) as sum,avg(goodsPrice) as avg')
	 	->group('goodsName')
	 	->order('count(goodsId) desc,sum(goodsPrice) desc')
	 	->select();
	 }
	 
	 /**
	  * 获取销售明细列表
	  * @param $page
	  * @param $pageSize
	  * @param $map
	  * @return mixed
	  */
	 public function OrderDetails($page,$pageSize,$map){
	 	$m = M('Orders');
	 	$offset = ($page-1) * $pageSize;
	 	return $m->join('LEFT JOIN oto_order_goods g ON oto_orders.orderId = g.orderId')
	 	->where($map)
	 	->field('g.goodsName,oto_orders.orderNo,goodsNums,goodsPrice,oto_orders.createTime')
	 	->limit($offset,$pageSize)
	 	->order('oto_orders.orderId desc,goodsNums desc,goodsPrice desc')
	 	->select();
	 	//echo $m->getLastSql();die;
	 }
	 
	 /**
	  * 获取销售明细总条数
	  * @param $map
	  * @return int
	  */
	 public function OrderDetailsCount($map){
	 	$m = M('Orders');
	 	$sql = 'select * from oto_orders  LEFT JOIN oto_order_goods  ON oto_orders.orderId=oto_order_goods.orderId WHERE '.$map;
	 	$count = $m->query($sql);
	 	return count($count);
	 }
	 
	 /**
	  * 导出销售明细报表
	  * @param $startDate
	  * @param $endDate
	  * @return mixed
	  */
	 public function derivedDetail($startDate,$endDate){
	 	$m = M('Orders');
	 	$where = "orderStatus = 4 ";
	 	if($startDate != ""){
	 		$where.="AND createTime >= '$startDate'";
	 	}
	 	if($endDate != ""){
	 		$where.="AND createTime < '$endDate'";
	 	}
	 	return $m->join('LEFT JOIN oto_order_goods g ON oto_orders.orderId = g.orderId')
	 	->where($where)
	 	->field('g.goodsName,oto_orders.orderNo,goodsNums,goodsPrice,oto_orders.createTime')
	 	->order('goodsNums desc,goodsPrice desc')
	 	->select();
	 }
};
?>